package com.tledu.springboot19.dao.impl;

import com.tledu.springboot19.dao.StudentDao;
import com.tledu.springboot19.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 加上这个注解声明这是一个dao层
 */
@Repository
public class StudentDaoImpl implements StudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Student> list(String name) {
        // 代表我们传进来了一个name，需要根据name进行筛选
        String sql;
        List<Map<String, Object>> list;
        if (name != null && !"".equals(name)) {
            sql = "select * from stu where name = ?";
            // 查询列表，并且把参数传递过去
            list = jdbcTemplate.queryForList(sql, name);
        } else {
            // 直接查询列表
            sql = "select * from stu";
            list = jdbcTemplate.queryForList(sql);
        }
        List<Student> students = new ArrayList<>();
        for (Map<String, Object> item : list) {
            // 构建对象
            Student stu = new Student();
            stu.setId((Integer) item.get("id"));
            stu.setName((String) item.get("name"));
            stu.setAge((Integer) item.get("age"));
            stu.setClassId((Integer) item.get("class_id"));
            stu.setSex((String) item.get("sex"));
            // 放到数组中
            students.add(stu);
        }

        return students;
    }

    @Override
    public void insert(Student student) {
        String sql = "insert into stu (name,age) value (?,?)";
        jdbcTemplate.update(sql, student.getName(), student.getAge());
    }
}
